<template>
  <div class="app-container">
    <div v-if="!noDreamFound" class="filter-container">
      <el-input v-model="listQuery.title"
                placeholder="Title" style="width: 200px;"
                class="filter-item"
                @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.isPrivate"
                 placeholder="Private" clearable
                 class="filter-item" style="width: 130px">
        <el-option v-for="item in privateSet" :key="item.value" :label="item.key" :value="item.value" />
      </el-select>
      <el-select multiple collapse-tags v-model="listQuery.level"
                 v-show="classificationCode.length>0"
                 placeholder="Classification" clearable
                 class="filter-item" style="width: 130px">
        <el-option v-for="item in classificationCode"
                :key="item.degree_code" :label="item.degree_code" :value="item.degree_code" />
      </el-select>
      <tags-input :only-existing-tags="true"
                  :typeahead="true"
                  placeholder="Search tags" :typeahead-hide-discard="true"
                  :add-tags-on-space="true"
                  typeahead-style="dropdown"
                  typeahead-url="http://192.168.56.1:5000/tags/api/v1/get_all_tags"
                  element-id="tags"
                  v-model="listQuery.tags"
      > </tags-input>
      <el-button type="primary" @click="handleFilter"> Search </el-button>
    </div>
    <el-table v-if="!noDreamFound" v-loading="listLoading"
              :data="filteredList.slice((listQuery.page-1)*listQuery.limit,listQuery.page*listQuery.limit)"
              element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column align="center" label="ID" width="95">
        <template slot-scope="{row}">
          {{ row.id }}
        </template>
      </el-table-column>

      <el-table-column label="Occur Time"
                       width="180" align="center"
                       :sortable="true" :sort-method="sortByDate">
          <template slot-scope="{row}">
            <span>{{ row.dream_date }}</span>
          </template>
        </el-table-column>

      <el-table-column label="Title">
        <template slot-scope="{row}">
          {{ row.title }}
        </template>
      </el-table-column>

        <el-table-column label="Private" width="110" align="center">
          <template slot-scope="{row}">
            <!-- <svg-icon v-if="row.is_private==true" icon-class="check" class="meta-item__icon" />
            <svg-icon v-else icon-class="close" class="meta-item__icon" /> -->
            <span v-if="row.is_private"> YES </span>
            <span v-else> NO </span>
          </template>
        </el-table-column>
      <el-table-column class-name="status-col" label="Tags" align="center">
        <template slot-scope="{row}">
          <el-tag v-for="tag in row.tags" :key="tag.key" type="info">{{ tag.value }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="Classification">
        <template slot-scope="{row}">
          <svg-icon icon-class="tree" />
          <span>{{ row.degree_info.degree_code }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="Action" width="400">
        <template slot-scope={row}>

          <router-link :to="'/nightmares/edit_dream/'+row._id">
            <el-button type="primary"> <i class="el-icon-edit" /> Edit </el-button>
          </router-link>

          <router-link :to="'/nightmares/read_dream/'+row._id">
            <el-button type="info"> <i class="el-icon-reading" /> Read </el-button>
          </router-link>

          <el-button type="danger" @click="deleteDream(row._id)">
            <i class="el-icon-delete" /> Delete </el-button>
        </template>
      </el-table-column>
    </el-table>
    <h1 v-else> No Dream found </h1>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchDreams" />
  </div>
</template>

<script>
import { getDreams, deleteDreamById } from '@/api/dreams'
import { getClassification } from '@/api/classification'
import Pagination from '@/components/Pagination'
import TagsInput from './components/tagsInput'
export default {
  components: { Pagination, TagsInput },
  data() {
    return {
      dreamList: [],
      filteredList: [],
      listLoading: false,
      noDreamFound: false,
      total: 0,
      classificationCode: [],
      candidateTags: [],
      privateSet: [{ key: 'YES', value: true },
                   { key: 'NO', value: false }],
      listQuery: {
        page: 1,
        limit: 20,
        title: '',
        isPrivate: '',
        level: [],
        tags:[]
      }
    }
  },

  watch: {
    listQuery: {
      handler(newVal, oldVal){
        this.ifResetSearch()
      },
      deep: true
    }
  },

  created() {
    this.fetchDreams()
  },
  methods: {
    // loadCandidateTags(){
    //   var keyTag = 0
    //   for (var i = 0; i < this.dreamList.length; ++i) {
    //     for (var j = 0; j < this.dreamList[i].tags.length; ++j) {
    //       var existValue = this.candidateTags.filter(tags => {
    //         return tags.value == this.dreamList[i].tags[j].value
    //       })
    //       if (existValue.length ==  0){
    //         this.candidateTags.push({ key: keyTag, value: this.dreamList[i].tags[j].value })
    //         keyTag = keyTag + 1
    //       }
    //     }
    //   }
    //   console.log('load candidate tags')
    //   console.log(this.candidateTags)
    // },
    fetchDreams() {
      this.listLoading = true
      getDreams().then(response => {
        console.log(response)
        if (response.data.length != 0){
          this.dreamList = response.data
          this.total = this.dreamList.length
          this.filteredList = this.dreamList
          console.log("total : " + this.total)
          for (var i = 1; i <= this.dreamList.length; ++i){
            this.dreamList[i - 1]['id'] = i
          }
          this.fetchClassification()
        } else {
          this.noDreamFound = true
        }
        this.listLoading = false
      })
    },
    fetchClassification() {
      this.listLoading = true
      getClassification().then(response => {
        console.log(response)
        if (response.code === 20000){
          if (response.data.title == 'default') {
            this.classificationCode = []
            this.listLoading = false
          } else {
            this.classificationCode = response.data.degree
            this.listLoading = false
            console.log('load classification code done: ')
            console.log(this.classificationCode)
          }
        }
      })
    },
    sortByDate(date1, date2){
      let val1 = date1.dream_date
      let val2 = date2.dream_date
      return val1 - val2
    },
    ifResetSearch() {
      if (this.listQuery.title== ''
          && this.listQuery.isPrivate == ''
          && this.listQuery.level.length == 0
          && this.listQuery.tags.length == 0){
        this.filteredList = JSON.parse(JSON.stringify(this.dreamList))
      }
      if (this.filteredList.length == 0) {
        this.filteredList = JSON.parse(JSON.stringify(this.dreamList))
      }
    },
    handleFilter() {
      console.log('filter...lists length: ' + this.filteredList.length + '|' + this.dreamList.length)
      console.log(this.listQuery)
      this.filteredList = JSON.parse(JSON.stringify(this.dreamList))

      if (this.listQuery.title && this.dreamList.length != 0) {
        console.log('filter title')
        this.filteredList = this.filteredList.filter(dream => {
          return dream.title.indexOf(this.listQuery.title) > -1
        })
      }
      if (this.listQuery.isPrivate != "" && this.filteredList.length != 0) {
        console.log('filter private')
        this.filteredList = this.filteredList.filter(dream => {
          dream.is_private == this.listQuery.isPrivate
        })
      }
      if (this.listQuery.level.length != 0 && this.filteredList.length != 0) {
        console.log('filter level...')
        this.filteredList = this.filteredList.filter(dream => {
            // return dream.degree_info.degree_code.indexOf(this.listQuery.level) > -1
          return this.listQuery.level.includes(dream.degree_info.degree_code)
        })
      }
      if (this.listQuery.tags.length != 0 && this.filteredList.length != 0) {
        this.candidateTags = []
        var delListIndex = []
        for (var i = 0; i < this.listQuery.tags.length; ++i) {
          this.candidateTags.push(this.listQuery.tags[i].value)
        }
        console.log('filter tags....')
        console.log(this.candidateTags)

        for (var i = 0; i < this.filteredList.length; ++i) {
          var currTagsList = []
          //push all tags value in a list to compare
          for (var j = 0; j < this.filteredList[i].tags.length; ++j) {
            currTagsList.push(this.filteredList[i].tags[j].value)
          }
          console.log(currTagsList)
          console.log('difference' + this.getArrDifference(this.candidateTags, currTagsList).length)
          var allLen = this.candidateTags.length + currTagsList.length
          if (this.getArrDifference(this.candidateTags, currTagsList).length == allLen) {
            console.log("no same tag")
            delListIndex.push(i)
          }
        }
        for (let i in delListIndex) {
          this.filteredList.splice(i, 1)
        }
        console.log("delete list: ")
        console.log(delListIndex)
      }
      console.log(this.filteredList.length)
    },
    getArrDifference(arr1, arr2) {
        return arr1.concat(arr2).filter(function(v, i, arr) {
            return arr.indexOf(v) === arr.lastIndexOf(v);
        });
    },
    deleteDream(id) {
      const data = { '_id' : id }
      deleteDreamById(data).then(response => {
        if (response.code === 20000){
          this.$router.go(0)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.filter-container{
  .tags-input-root{
    display: inline-block;
  }
}
.el-tag{
  margin: 5px;
}
.tags-input-root{
  display: inline-block;
}
.el-tag.el-tag--info{
  background-color: #111113;
  border-color: #e9e9eb;
  color: #e7efff
}

.filter-container{
  padding: 20px;
}
</style>
